package com.yeban.javase.day16.sync;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/30
 *
 * 需求：卖票   确保票源Ticket线程安全
 * 1.所有人不可以买到重复票源
 * 2.不可以买到负数的票号
 */
public class SyncTest {

    public static void main(String[] args) {
        Ticket ticket1 = new Ticket();
        Ticket ticket2 = new Ticket();
        Ticket ticket3 = new Ticket();
        Ticket ticket4 = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket1.sale();
            }
        },"A窗口").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket2.sale();
            }
        },"B窗口").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket3.sale();
            }
        },"C窗口").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket4.sale();
            }
        },"D窗口").start();
    }

}

class Ticket {
    private static int num = 30;

    /*// 同步方法
    public synchronized void sale() {
        if(num > 0) {
            System.out.println(Thread.currentThread().getName() + "卖了一张票，票号：" + (num--) + "，还有" + num + "张票");
        }
    }*/

    // 同步代码块    Ticket.class/this
    public void sale() {
        synchronized (Ticket.class) {
            if(num > 0) {
                System.out.println(Thread.currentThread().getName() + "卖了一张票，票号：" + (num--) + "，还有" + num + "张票");
            }
        }
    }
}